Java while & do???while loop

In this tutorial, we shall see how to use the while and do-while loop with example programs.

Java while loop

The while loop takes a condition and run the block of codes until the condition is satisfied.

Syntax for while loop

while (condition) {
    // body of the loop
}

Here, if the condition is true then, the block of code will be executed. If the condition if false then it will exit from the while loop.

The while loop checks the condition for every iteration before running the block of code.

Example program for while loop

// Program to display numbers from 1 to 10

class Main {
  public static void main(String[] args) {

    // declare variables
    int i = 1, number = 10;

    // while loop from 1 to 10
    while(i <= number) {
      System.out.println(i);
      i++;
    }
  }
}

Output

1
2
3
4
5
6
7
8
9
10

In the above program, the while loop will check whether the value of i is lesser than or equal to number. If it is true, print the value of i and increment the value of i by 1.

Again check the value of i with number. If it is true, print the value of i and increment the value of i by 1.

The above steps will be repeated until the value of i is greater than number. When the condition gets false, it will exit from the while loop.

Java do-while loop

The do-while loop is similar to while loop, However, before the test condition is verified in this case, the do-while loop's body is run once.

Syntax for do-while loop

do {
  // body of the loop
}
while (condition);

Here, the body of the loop is executed first and then the while loop will check the condition and controls the further iteration.

Example for do-while loop

// Program to display numbers from 1 to 10

class Main
{
  public static void main (String[]args)
  {

    // declare variables
    int i = 1, number = 10;

    // do-while loop from 1 to 10
    do
    {
    	System.out.println (i);
    	i++;
    }while (i <= number);
  }
}

Output

1
2
3
4
5
6
7
8
9
10

Example 2 for do-while loop

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int number = -1;

    // create an object of Scanner class
    Scanner input = new Scanner(System.in);
	   
    // do...while loop continues 
    // until entered number is positive
    do {
        // To handle initial entry.
      if(number>0){
        System.out.println("Positive number");
      }
      System.out.println("Enter the positive number");
      number = input.nextInt();

    } while(number >= 0); 
	System.out.println("Program exit.");
    input.close();
  }
}

This program will repeatedly gets input from the user until the input number is a positive number.

Initially we have set the number value to be -1. But since do-while loop executes once initially, it will enter into the loop with negative value.

Output

Enter the positive number
5
Positive number
Enter the positive number
-2
Program exit.

Most Read